Array.prototype.in_array = function(e)
{
  for(i=0;i<this.length && this[i]!=e;i++);
  return !(i==this.length);
}

function showModal(res, _btn)
{
  var t = $('#myModal')
  .on('show.bs.modal', function (e) {
    // do something...
    $(this).find('.file-content').html('');
    console.info('show.bs.modal', e);
  })
  .modal('toggle')
  .on('shown.bs.modal', function (e) {
    // do something...
    var _modal = $(this);
    _modal.find('.load-filename').html(_btn.siblings('.filename').text());
    // _modal.find('.file-content').append(res.data.content);
    _modal.find('.file-content').html(res.data.content);
    _modal.find('.gif-loading').hide();
    // console.info('shown.bs.modal', this, t);
  })
  .on('hide.bs.modal', function (e) {
    // do something...
    console.info('hide.bs.modal');
  })
  .on('hidden.bs.modal', function (e) {
    // do something...
    $(this).find('gif-loading').show();
    console.info('hidden.bs.modal');
  });
}

function showAlert(box, args) {
  var args = $.extend({
        type: 'warning',// info success primary danger
        title:'Warning!',
        msg:'',
        enableClose:true
      }, args),
      box = typeof box == 'string' ? $(box) : box;
  var button = '';
  if ( args.enableClose ) {
    button = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
  }
  var html = '<div class="alert alert-' + args.type + ' alert-dismissible" role="alert">'
      + button
      +'<strong>' + args.title + '</strong>' + args.msg
      +'</div>';

  if ( box[0] ) {
    box.append(html);
  } else {
    console.error('target box element don\'t exists!');
  }
}

$(function(){

  // preview
  $('ul').on('click', 'a.preview-file', function (e) {
    var _btn = $(this);
    var _data = actVM.collectFormData();
    actVM.response.isOk = false;

    if ( !_data.web.className ) {
      return;
    }

    _data.type = _btn.data('type');
    console.info(_data);

    $.ajax({
      url: '/acttool/manager/preview',
      type: 'post',
      data: _data,
      dataType: 'json',
      success:function(res){
        if (res.code) {
          showAlert('.show-error',{msg: res.msg});
          if (('redirect' in res.data) && res.data.redirect) {
            setTimeout(function() {
              location.href = res.data.redirect;
            },2000);
          }
        } else {
          showModal(res, _btn);
        }
      }
    })

  });

  // generate files
  $('#generateFiles').click(function (e) {
    var _btn = $(this);
    var _data = actVM.collectFormData(true);

    actVM.response.isOk = false;
    if ( !_data.web.className ) {
      return;
    }

    console.info(_data);

    $.ajax({
      url: '/acttool/manager/create',
      type: 'post',
      data: _data,
      dataType: 'json',
      success:function(res){
        if (res.code) {
          showAlert('.show-error',{msg: res.msg});

          if ( ('redirect' in res.data) && res.data.redirect ) {
            setTimeout(function() {
              location.href = res.data.redirect;
            },2000);
          }
        } else {
          showAlert('.show-error',{type:'success', title:'Successful!', msg: res.msg});
          actVM.response.isOk = true;
          actVM.result = res.data.result;
        }
      }
    })

  });

});

var actVM = new Vue({
  el: '#J-activity',

  // 数据
  data: {
    errors : {
      className : '请输入活动类名称(class name)！',
      msg : ''
    },
    response : {
      isOk : false,
      pageUrl:''
    },
    result : {
      generate : [],
      skip : [],
      override : []
    },

    showViews: true,
    overrideOld: true,
    paths: GVar.paths,
    types: [],
    activityName:'',
    web: {
      parentClass: [],
      className:'',
      createMethod:1,
      subdir:'',
      activityStart:1,
      activityEnd:0,
      viewFolder:''
    },
    svr: {
      className:'',
      subdir:'',
      parentClass: 'ActivityBase'
    }
  },

  // 计算属性
  computed:{
    canableVisitView:function() {
      // 同时创建了控制器和视图
      return this.types.in_array(1) && this.types.in_array(2);
    },
    activityPageUrl : function() {
      var url = '';
      if ( this.showViews ) {
        url += this.web.subdir ? this.lcfirst(this.web.subdir) + '/' : '';
        url += this.lcfirst(this.web.className);
        url = this.paths.projectUrl + '/app/activity/' + url;
      }

      return url;
    },
    webClassName: {
      get:function() {
        return this.web.className;
      },
      set:function(newValue) {
        this.web.className = newValue ? this.ucfirst(newValue).trim() : '';
      }
    },
    webControllerPath:function(){
      if ( this.web.subdir ) {
        return this.paths.webControllerPath + '/' + this.web.subdir;
      } else {
        return this.paths.webControllerPath;
      }
    },
    webControllerFile:function(){
      if (this.web.className) {
        return this.ucfirst(this.web.className) + '.php';
      }
      return this.errors.className;
    },
    webViewFolder:{
      get:function(){
        return this.web.viewFolder ? this.web.viewFolder : this.web.className.toLowerCase();
      },
      set:function(val) {
        this.web.viewFolder = val.trim();
      }
    },
    webViewPath:function(){
      if ( this.webViewFolder ) {
          if (this.web.subdir ) {
            return this.paths.viewsPath + '/' + this.web.subdir.toLowerCase() + '/' + this.webViewFolder;
          } else {
            return this.paths.viewsPath + '/' + this.webViewFolder;
          }
      }

      return this.errors.className;
    },
    svrClassName: {
      get:function() {
        return this.svr.className ? this.svr.className : this.web.className;
      },
      set:function(newValue) {
        this.svr.className = newValue ? this.ucfirst(newValue) : '';
      }
    },
    svrControllerPath:function(){
      if ( this.web.subdir ) {
        return this.paths.svrControllerPath + '/' + this.web.subdir;
      } else {
        return this.paths.svrControllerPath;
      }
    },
    svrControllerFile:function(){
        return this.svrClassName ? this.ucfirst(this.svrClassName) + '.php' : this.webControllerFile;
    }
  },

  // 方法
  methods: {
      // 首字母 大写
    ucfirst : function(str) {
      return str.substr(0,1).toUpperCase() + str.slice(1);
    },
      // 首字母 小写
    lcfirst : function(str) {
      return str.substr(0,1).toLowerCase() + str.slice(1);
    },
    toggleViews : function() {
      this.showViews = !this.showViews;
    },
    getFullPathFile : function(file, path) {
      return path + '/' + file;
    },
    showAlert : function(el, args) {
      return path + '/' + file;
    },
    collectFormData: function(_needFile) {
        var _needFile = _needFile || false;
        var _form = {
            // web: this.web,
            web: this.$data.web,
            svr: this.$data.svr
        };

        // to json object
        _form = JSON.parse(JSON.stringify(_form));

        _form.web.activityName =_form.svr.activityName = this.activityName;
        _form.web.viewFolder = this.webViewFolder;
        _form.web.webViewPath = this.webViewPath;

        _form.svr.className = this.svrClassName;
        _form.svr.subdir = this.web.subdir;

        if ( _needFile ) {
          _form.overrideOld = this.overrideOld ? 1 : 0;
          _form.types = this.types;
          _form.files = {
            1 : this.getFullPathFile(this.webControllerFile, this.webControllerPath),
            2 : this.webViewPath + '/index.php',
            3 : this.getFullPathFile(this.svrControllerFile, this.svrControllerPath),
          };
        }

        return _form;
    }
  }

});
